package me.report.api.web.controller.admin;

import com.mongodb.gridfs.GridFSDBFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import me.report.api.mongodb.service.MongoService;
import me.report.mongodb.model.Report;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author ME
 */
@Controller
@RequestMapping("/report/action")
public class ReportActionController {
    @Autowired 
    MongoService mongoService;
    
    Logger logger = Logger.getLogger(getClass());
    
     @RequestMapping(value = "/add")
    public String reportAdd() {
        return "report/action/add";
    }

    @RequestMapping(value = "/modify/{reportId}")
    public @ResponseBody
    ModelAndView modifyReport(
            @PathVariable("reportId") String reportId,
            HttpServletRequest request) {

        // lay thong tin report tu reportId
        Report report = mongoService.getReportByID(reportId);

        // dua thong tin report sang html
        Map map = new HashMap<String, Object>();
        map.put("report", report);

        // lay thong tin file tu reportId
        GridFSDBFile reportFile = mongoService.getReportFileById(report.getReportIdFile());
        try {
            String reportContent = IOUtils.toString(reportFile.getInputStream(), "UTF-8");
            map.put("reportContent", reportContent);
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }

        return new ModelAndView("report/action/modify", map);
    }

    @RequestMapping(value = "/modified", method = RequestMethod.POST)
    public ModelAndView reportModified(
            HttpServletRequest request) {

        try {
            // lay thong tin reportContent
            String reportContent = request.getParameter("reportContent");
            InputStream is = new ByteArrayInputStream(reportContent.getBytes(Charset.forName("UTF-8")));

            // lay thong tin reportId
            String reportId = request.getParameter("reportId");

            Report report = mongoService.getReportByID(reportId);
            mongoService.deleteReportFileByIdFile(report.getReportIdFile());
            String storeId = mongoService.saveReportFile(is, report.getReportName());
            report.setReportIdFile(storeId);
            mongoService.updateReportById(report);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return new ModelAndView("redirect:/admin/report");
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public @ResponseBody
    ModelAndView reportSave(HttpServletRequest request) {

        // tra lai thong tin model va view tiep theo
        ModelAndView mv = new ModelAndView("redirect:/admin/report");

        // lay thong tin report tu request
        Report report = new Report();
        report.setReportName(request.getParameter("reportName"));
        report.setReportDescription(request.getParameter("reportDescription"));

        // lay thong tin id
        String reportId = request.getParameter("reportId");

        // lay thong tin file upload 
        final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        MultipartFile reportFile = multiRequest.getFile("reportFile");

        // kiem tra file null
        if (!StringUtils.hasText(reportFile.getOriginalFilename())) {

        } else {
            try {
                String storeId = mongoService.saveReportFile(reportFile.getInputStream(),
                        reportFile.getOriginalFilename());
                // get report file id
                report.setReportIdFile(storeId);
            } catch (IOException ex) {
                logger.error(ex.getMessage());
            }
        }

        // lua chon add va update neu khong co reportId
        if (!StringUtils.hasText(reportId)) {
            // service to save report
            mongoService.addReport(report);
        } else {
            report.setReportId(reportId);
            mongoService.updateReportById(report);
        }
        return mv;
    }

    @RequestMapping(value = {"/delete/{reportId}"}, method = RequestMethod.GET)
    public @ResponseBody
    ModelAndView reportDelete(@PathVariable("reportId") String reportId,
            HttpServletRequest request) {

        // thiet lap trang view moi
        ModelAndView mv = new ModelAndView("redirect:/admin/report");

        mongoService.deleteReportById(reportId);
        return mv;
    }

    @RequestMapping(value = {"/edit/{reportId}"}, method = RequestMethod.GET)
    public @ResponseBody
    ModelAndView reportEdit(@PathVariable("reportId") String reportId) {

        // lay thong tin report tu reportId
        Report report = mongoService.getReportByID(reportId);

        // khoi tao model cho view
        Map model = new HashMap<String, Object>();
        model.put("report", report);

        return new ModelAndView("report/action/add", model);
    }
}
